package com.collapse.union.gitee.liteflow.design.demo.config;

import com.yomahub.liteflow.springboot.config.LiteflowMainAutoConfiguration;
import com.yomahub.liteflow.springboot.config.LiteflowPropertyAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Map;

@Configuration
@AutoConfigureBefore(value = {LiteflowPropertyAutoConfiguration.class, LiteflowMainAutoConfiguration.class})
public class DataSourceInitializer {
    private static final Logger log = LoggerFactory.getLogger(DataSourceInitializer.class);

    @Autowired
    private DataSource dataSource;

    @Value("classpath:sql/ddl-mysql.sql")
    private Resource ddlMysql;

    @Value("classpath:sql/dml-mysql.sql")
    private Resource dmlMysql;

    @Value("classpath:sql/dml-pg.sql")
    private Resource dmlPg;

    @Value("classpath:sql/ddl-pg.sql")
    private Resource ddlPg;

    @Value("classpath:sql/dml-h2.sql")
    private Resource dmlH2;

    @Value("classpath:sql/ddl-h2.sql")
    private Resource ddlH2;

    @PostConstruct
    public void startDbInitializer() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        try {
            Map map = jdbcTemplate.queryForMap("select count(1) from chain_info");
        } catch (Exception e) {
            Connection conn = null;
            DatabaseMetaData metaData = null;
            try {
                conn = dataSource.getConnection();
                metaData = conn.getMetaData();
                String productName = metaData.getDatabaseProductName();
                productName = productName.toLowerCase();
                // 报错,表不存在,初次导入，则执行相关脚本
                if ("mysql".equals(productName)) {
                    initSql(ddlMysql);
                    initSql(dmlMysql);
                } else if ("postgresql".equals(productName)) {
                    initSql(ddlPg);
                    initSql(dmlPg);
                } else if ("h2".equals(productName)) {
                    initSql(ddlH2);
                    initSql(dmlH2);
                } else {
                    initSql(ddlPg);
                    initSql(dmlPg);
                }
            } catch (Exception e1) {
                log.warn("---------->数据源类型，获取失败-->:", e);
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                    }
                } catch (SQLException e1) {
                }
            }
        }
    }

    private void initSql(Resource resource) {
        log.info("---------->初始化脚本，开始执行-->:" + resource.getFilename());
        try {
            Connection conn = DataSourceUtils.getConnection(dataSource);
            EncodedResource er = new EncodedResource(resource, "utf-8");
            ScriptUtils.executeSqlScript(conn, er);
            log.warn("---------->初始化脚本，执行完成-->:" + resource.getFilename());
        } catch (Exception e) {
            log.warn("---------->初始化脚本，执行失败-->:", e);
        }
    }
}
